package com.elcom.roaming.common.util.match;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;

import com.elcom.roaming.common.config.ConfigModule;

public class CleaningMap implements Runnable{
	
	private ConcurrentHashMap<ObjectKey, ObjectValue> map;
	private Logger logger;
	private boolean stop;
	
	public CleaningMap(Logger logger, ConcurrentHashMap<ObjectKey, ObjectValue> map) {
		this.logger = logger;
		this.map = map;
		this.stop = false;
	}
	
	@Override
	public void run() {
		while (!stop) {
			try {
				Thread.sleep(ConfigModule.MATCHING_CLEANING_MAP_TIME/2 * 1000);
			} catch (InterruptedException e) {
				logger.error("Sleep error.", e);
			}
			logger.info("Cleaning begin...");

			if (map.size() == 0){
				logger.info("Nothing to remove...");
				logger.info("Cleaning end.");
				continue;
			}
			
			long curTime = getCurTime();
			long sysTime = System.currentTimeMillis();
			if (sysTime - curTime > ConfigModule.MATCHING_CLEANING_MAP_TIME * 2 * 1000)
				curTime = sysTime; 
			
			ArrayList<ObjectKey> removeKeys = new ArrayList<ObjectKey>();
			Iterator<ObjectKey> iter = map.keySet().iterator();
			while (iter.hasNext()){
				ObjectKey key = iter.next();
				if (curTime - key.getPutTimeInMs() > ConfigModule.MATCHING_CLEANING_MAP_TIME * 1000) removeKeys.add(key);
			}
			
			int removeSize = removeKeys.size();
			for (ObjectKey key : removeKeys) {
				map.remove(key);
			}
			logger.info("Remove " + removeSize + " out of date objects.");
			logger.info("Cleaning end.");
		}
	}
	
	private long getCurTime(){
		Iterator<ObjectKey> iter = map.keySet().iterator();
		long time = 0;
		while (iter.hasNext()){
			ObjectKey key = iter.next();
			long last = key.getPutTimeInMs();
			if (last > time) time = last;
		}
		
		return time;
	}
	
}
